package com.dotndot.momserver.servlet;

import java.io.*;
import java.text.*;
import java.util.*;
import java.util.logging.*;

import javax.jdo.*;
import javax.jdo.Query;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.util.*;

import com.dotndot.momserver.data.*;
import com.dotndot.momserver.request.*;
import com.dotndot.momserver.response.*;
import com.dotndot.momserver.utils.*;
import com.google.appengine.api.datastore.*;
import com.google.appengine.api.images.*;

@SuppressWarnings( "serial" )
public class BabyServlet extends HttpServlet
{

    private static final Logger log = Logger.getLogger(BabyServlet.class.getName());

    @Override
    protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
    {
        String path = req.getRequestURI();
        if( path.equals("/baby/avatar.dnd") )
        {
            babyAvatar(req, resp);
        }
    }
    
    @Override
    public void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
    {

        String path = req.getRequestURI();
        boolean isMultipart = Utils.get().isMultipartContent(req);
        resp.setCharacterEncoding("UTF-8");
        
        if( isMultipart )
        {
            if( path.equals("/baby/add.dnd") )
            {
                addBaby(req, resp);
            }
        }
        else
        {
            if( path.equals("/baby/list.dnd") )
            {
                babyList(req, resp);
            }            
        }

    }
    
    public void addBaby( HttpServletRequest req, HttpServletResponse resp )
    {

        try
        {
            String momIndex = null;
            String name = null;
            String gender = null;
            String birthday = null;
            Date date = null;
            Blob avatar = null;

            ServletFileUpload upload = new ServletFileUpload();

            FileItemIterator iterator;
            iterator = upload.getItemIterator(req);

            while( iterator.hasNext() )
            {
                FileItemStream item = iterator.next();
                InputStream istream = item.openStream();
                if( item.isFormField() )
                {
                    if( item.getFieldName().equals(Request.BABY_ADD_MOM_INDEX_PARAM) )
                    {
                        momIndex = Streams.asString(istream, "UTF-8");
                    }
                    else if( item.getFieldName().equals(Request.BABY_ADD_NAME_PARAM) )
                    {
                        name = Streams.asString(istream, "UTF-8");
                    }
                    else if( item.getFieldName().equals(Request.BABY_ADD_GENDER_PARAM) )
                    {
                        gender = Streams.asString(istream, "UTF-8");
                    }
                    else if( item.getFieldName().equals(Request.BABY_ADD_BIRTHDAY_PARAM) )
                    {
                        birthday = Streams.asString(istream, "UTF-8");
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        try
                        {
                            date = format.parse(birthday);
                        }
                        catch( ParseException e )
                        {
                            e.printStackTrace();
                        }
                    }
                }
                else
                {
                    if( item.getFieldName().equals(Request.BABY_ADD_AVATAR_PARAM) )
                    {
                        Image image = Utils.get().getInputStreamToImage(istream);
                        avatar = Utils.get().getRawImageData(image);
                    }
                }
            }

            Response response = null;
            PrintWriter out = null;
            
            try
            {
                resp.setContentType("text/plain");
                out = resp.getWriter();
            }
            catch( IOException e )
            {
                e.printStackTrace();
            }
            
            Baby baby = null;
            baby = new Baby(Long.valueOf(momIndex), name, gender, date, avatar);

            PersistenceManager pm = PMF.get().getPersistenceManager();
            pm.makePersistent(baby);
            pm.close();
            
            response = new Response(Response.Status.OK, Response.Code.S000, Response.Message.RET_BABY_ADD_SUCCESS);
            out.print(response.toJson());

        }
        catch( FileUploadException e )
        {
            e.printStackTrace();
        }
        catch( IOException e )
        {
            e.printStackTrace();
        }
    }    
    
    public void babyList( HttpServletRequest req, HttpServletResponse resp )
    {
        Response response = null;
        PrintWriter out = null;

        try
        {
            resp.setContentType("text/plain");
            out = resp.getWriter();
        }
        catch( IOException e )
        {
            e.printStackTrace();
        }
        
        List<Baby> items = null;
        String momIndexText = req.getParameter(Request.BABY_LIST_MOM_INDEX_PARAM);
        Long momIndex = Long.valueOf(momIndexText);
        
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Baby.class);
        query.setFilter("momIndex == momIndex_");
        query.declareParameters("Long momIndex_");
        items = (List<Baby>) query.execute(momIndex);   
        
        if( items.size() != 0 )
        {
            List<ResBaby> resBaby = new ArrayList<ResBaby>(); 
            for(Baby baby : items){
                resBaby.add(new ResBaby(baby.getIndex(), baby.getName(), baby.getBirthday(), (baby.getAvatar() != null)?true:false));
            }
            response = new Response(Response.Status.OK, Response.Code.S000, Response.Message.RET_BABY_LIST_SUCCESS, resBaby);
        }else{
            response = new Response(Response.Status.OK, Response.Code.S000, Response.Message.RET_BABY_LIST_SUCCESS, null);
        }
        
        query.closeAll();
        pm.close();
        out.print(response.toJson());

    }    

    public void babyAvatar( HttpServletRequest req, HttpServletResponse resp )
    {

        String indexStr = req.getParameter(Request.PARAM_INDEX);
        Long index = Long.valueOf(indexStr);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Baby.class);
        query.setFilter("index == index_");
        query.declareParameters("Long index_");

        try
        {
            List<Baby> items = (List<Baby>) query.execute(index);

            if( items.size() != 0 )
            {
                Blob image = items.get(0).getAvatar();
                if(image != null){
                    resp.setContentType("image/jpeg");
                    resp.getOutputStream().write(image.getBytes());
                }
            }
        }
        catch( IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            query.closeAll();
            pm.close();
        }
    }    
}
